package com.itzmn.newcode.offer;

import java.util.Stack;

/**
 * @Author: 张梦楠
 * @Date: 2018/11/15 10:46
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description: 剑指Offer 包含min函数的栈
 *
 *  在栈中实现min函数，打印栈中最小的数据
 *
 */
public class SearchStackMin {



    //数据栈，用于存储数据
    Stack<Integer> s1 = new Stack<>();
    // 辅助栈，用于记录栈中的最小值
    Stack<Integer> temp = new Stack<>();

    public static void main(String[] args) {

        new SearchStackMin().init();
    }
    public void init(){

        push(3);
        System.out.println(min());
        push(4);
        System.out.println(min());
        push(2);
        System.out.println(min());
        push(3);
        System.out.println(min());
        pop();
        System.out.println(min());
        pop();
        System.out.println(min());
        pop();
        System.out.println(min());
        push(0);
        System.out.println(min());

    }

    public void push(int node) {



        if (s1.isEmpty()){
            temp.push(node);
        }else {
            Integer peek = temp.peek();
            //当传入的值小于等于辅助站的时候，辅助栈也需要入栈
            if (node <= peek){
                temp.push(node);
            }
        }
        s1.push(node);
    }

    public void pop() {

        if (s1.isEmpty()){
            return;
        }

        Integer top = top();
        if (top.equals(null)){
            return;
        }

        Integer peek = temp.peek();
        //如果数据栈弹出的数据和辅助栈的栈顶是一样大的，就弹出
        if (top.equals(peek) ){
            temp.pop();
        }

        s1.pop();
    }

    public int top() {

        if (s1.isEmpty()){
            return (Integer)null;
        }
        return s1.peek();
    }

    public int min() {

        return temp.peek();

    }



}
